<template>
  <div class="form-page">
    <Card :bordered="false" :dis-hover="true">
      <p slot="title" style="color: #666;">
        <span
          class="iconfont icon-changyongtubiao-xianxingdaochu-zhuanqu-"
          style="font-size: 20px;"
        ></span> 品牌商信息
      </p>
      <p slot="extra" style="color: #999;font-size: 12px;">
        <label style="color: #FF3B30;">*</label> 为必填
      </p>

      <div class="company-box">
        <div>
          <Row type="flex" justify="start" align="middle">
            <div class="divider-short"></div>
            基本信息
          </Row>
          <Form ref="formModel" :rules="ruleValidate" :model="bloc.form.company" :label-width="100"
                label-position="right">
            <FormItem label="品牌商名称:" prop="name" required>
              <Input type="text" v-model="bloc.form.company.name" placeholder="请填写品牌商名称"
                     style="width: 400px;height: 40px;"/>
            </FormItem>
            <FormItem label="品牌商简称:" prop="shortName" required>
              <Input type="text" v-model="bloc.form.company.shortName" placeholder="请填写简称" style="width: 400px"/>
            </FormItem>
            <FormItem label="品牌商网址:">
              <Input type="text" v-model="bloc.form.company.clientUrl" placeholder="请填写品牌商网址" style="width: 400px"/>
            </FormItem>
            <FormItem label="所属区域:" prop="addressInfo" required>
              <al-cascader data-type="all"
                           v-model="bloc.addressItems"
                           @on-change="data=>bloc.addressInfo=data"
                           level="2"
                           style="width: 400px"/>
            </FormItem>
            <FormItem label="详细地址:">
              <Input type="text" v-model="bloc.form.company.address" placeholder="请填写详细地址" style="width: 400px"/>
            </FormItem>
          </Form>
        </div>
        <div>
          <Row type="flex" justify="start" align="middle">
            <div class="divider-short"></div>
            品牌商管理员
          </Row>
          <Form ref="formOtherModel" :rules="ruleOtherValidate" :model="bloc.form.account" :label-width="100"
                label-position="right">
            <FormItem label="联系人姓名:" prop="userName" required>
              <Input type="text" v-model="bloc.form.account.userName" placeholder="请填写联系人姓名"
                     style="width: 400px;height: 40px;"/>
            </FormItem>
            <FormItem label="手机号码:">
              <Input type="text" v-model="bloc.form.account.phone" placeholder="请填写手机号码" style="width: 400px"/>
            </FormItem>
            <FormItem label="登录账号:" prop="email" required>
              <Input type="text" v-model="bloc.form.account.email" placeholder="请填写登录账号，邮箱格式" style="width: 400px"/>
            </FormItem>
            <FormItem label="登录密码:" prop="password" v-if="isAdd" required>
              <Input type="password" autocomplete='new-password' v-model="bloc.form.account.password"
                     placeholder="请填写登录密码" style="width: 400px"/>
            </FormItem>
            <FormItem label="重复密码:" prop="repeatPassword" v-if="isAdd" required>
              <Input type="password" autocomplete='new-password' v-model="bloc.form.account.repeatPassword"
                     placeholder="请再次填写登录密码"
                     style="width: 400px"/>
            </FormItem>
            <FormItem label="权限角色:" prop="roles" required>
              <RoleSelector
                :tagCount="3"
                :roles="bloc.form.account.roles"
                @on-change="value=>bloc.form.account.roles=value"></RoleSelector>
            </FormItem>
          </Form>
        </div>
      </div>
      <div style="margin: 20px 0px 35px 25px; text-align: center!important;">
        <router-link :to="{ path: '/company'}">
          <Button style="width: 100px;height: 40px; ">返回</Button>
        </router-link>
        <Button type="primary" style="margin-left: 30px;width: 100px;height: 40px;" :loading="btnload.loading"
                @click="handleOk()">保存
        </Button>
      </div>

    </Card>
  </div>
</template>

<script lang="ts">
  import {Component, Vue} from 'vue-property-decorator';
  import {Route} from 'vue-router';
  import {FormBloc} from '@/view/company/FormBloc';
  import {isEmpty} from '@/base/util/Strings';
  import RoleSelector from '@/component/RoleSelector.vue';
  import {getValidateMaxString, getValidatePhone, getValidatePsd} from '@/base/util/Validate';
  import {Loading} from '@/base/Loading';

  @Component({components: {RoleSelector}})
  export default class extends Vue {
    beforeRouteEnter(to: Route, from: Route, next: (vm: any) => void) {
      next(vm => {
        if (!vm.isAdd) vm.bloc.load(vm.idx);
      });
    }

    get isAdd() {
      return !this.idx;
    }

    get idx() {
      return Number(this.$route.params.id);
    }

    bloc: FormBloc = new FormBloc();
    btnload = new Loading();
    validateAddress = (rule: any, value: string, callback: any) => {
      this.bloc.addressInfo.length === 0
        ? callback(new Error('请选择所属区域。')) : callback();
    };
    validateRepeatPassword = (rule: any, value: string, callback: any) => {
      isEmpty(this.bloc.form.account.repeatPassword) ||
      this.bloc.form.account.password !== this.bloc.form.account.repeatPassword
        ? callback(new Error('前后密码输入不一致。')) : callback();
    };
    validatePsd = (rule: any, value: string, callback: any) => {
      if (isEmpty(value)) return callback(new Error('密码不能为空'));
      if (!getValidatePsd(value)) return callback(new Error('密码由字母、数字、下划线组成且长度为6-20'));
      return callback();
    };
    ruleValidate = {
      name: [
        {required: true, message: '品牌商名称不能为空', trigger: 'blur'},
        {type: 'string', max: 15, message: '品牌商名称不能超过15个字', trigger: 'blur'}
      ],
      shortName: [
        {required: true, message: '品牌商简称不能为空', trigger: 'blur'},
        {type: 'string', max: 5, message: '品牌商简称不能超过5个字', trigger: 'blur'}
      ],
      addressInfo: [
        {validator: this.validateAddress, trigger: 'change'}
      ]
    };
    ruleOtherValidate = {
      userName: [
        {required: true, message: '联系人姓名不能为空', trigger: 'blur'},
        {type: 'string', max: 10, message: '联系人姓名不能超过20个字', trigger: 'blur'}
      ],
      email: [
        {required: true, message: '登录账号不能为空', trigger: 'blur'},
        {type: 'email', message: '邮箱格式不正确', trigger: 'blur'}
      ],
      password: [
        {required: true, validator: this.validatePsd, trigger: 'blur'}
      ],
      repeatPassword: [
        {validator: this.validateRepeatPassword, trigger: 'change'}
      ],
      roles: [
        {required: true, type: 'array', min: 1, message: '请选择一个角色', trigger: 'change'}
      ]
    };

    handleCancel() {
      this.$router.push({path: '/company'});
    }

    handleOk() {
      const formRef: any = this.$refs['formModel'];
      const formOtherRef: any = this.$refs['formOtherModel'];
      formRef.validate((valid) => {
        if (valid) {
          formOtherRef.validate((otherValid) => {
            if (otherValid) {
              this.saveFn();
            }
          });
        }
      });
    }

    getValidate() {
      if (!isEmpty(this.bloc.form.company.address) && getValidateMaxString(20, this.bloc.form.company.address)) {
        this.$Message.error('详细地址的长度不能超过20');
        return true;
      }
      if (!isEmpty(this.bloc.form.company.clientUrl) && getValidateMaxString(20, this.bloc.form.company.clientUrl)) {
        this.$Message.error('品牌商网址的长度不能超过20');
        return true;
      }
      if (!isEmpty(this.bloc.form.account.phone) && !getValidatePhone(this.bloc.form.account.phone)) {
        this.$Message.error('请输入正确的手机号码');
        return true;
      }
    }

    saveFn() {
      if (this.getValidate()) return;
      this.btnload.loading = true;
      const parmas = this.isAdd ? '' : this.idx;
      this.bloc.save(parmas).then(res => {
        this.$Message.success('保存成功');
        this.btnload.loading = false;
        this.handleCancel();
      }).catch(err => {
        this.btnload.loading = false;
        this.$Message.error('保存失败');
        console.log('出错啦::::', err);
      });
    }
  }
</script>

<style lang="less" scoped>
  .company-box {
    display: flex;
    justify-content: space-around;
  }

  .divider-short {
    width: 4px;
    height: 24px;
    background: #0079FE;
    margin-right: 10px;
  }

  .ivu-row-flex-middle {
    font-weight: bolder;
    font-size: 16px;
    margin-bottom: 28px;
  }

  .ivu-card-body > div {
    text-align: left !important;
  }

</style>
